package com.tduck.cloud.security.service;

import cn.hutool.core.util.ObjectUtil;
import com.tduck.cloud.common.entity.security.LoginUserEntity;
import com.tduck.cloud.common.entity.security.SysUserVO;
import com.tduck.cloud.common.exception.BaseException;
import com.tduck.cloud.common.util.JsonUtils;
import com.tduck.cloud.system.entity.SysUserEntity;
import com.tduck.cloud.system.entity.enums.UserStatusEnum;
import com.tduck.cloud.system.service.SysUserService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

/**
 * 用户验证处理
 *
 * @author smalljop
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class UserDetailsServiceImpl implements UserDetailsService {

    private final SysUserService userService;

    private final SysPermissionService permissionService;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        SysUserEntity user = userService.getUserByUserName(username);
        if (ObjectUtil.isNull(user)) {
            log.info("登录用户：{} 不存在.", username);
            throw new UsernameNotFoundException("登录用户：" + username + " 不存在");
        } else if (UserStatusEnum.DELETED.getCode().equals(user.getDelFlag())) {
            log.info("登录用户：{} 已被删除.", username);
            throw new BaseException("对不起，您的账号：" + username + " 已被删除");
        } else if (UserStatusEnum.DISABLE.getCode().equals(user.getStatus())) {
            log.info("登录用户：{} 已被停用.", username);
            throw new BaseException("对不起，您的账号：" + username + " 已停用");
        }
        return createLoginUser(user);
    }

    public UserDetails createLoginUser(SysUserEntity user) {
        SysUserVO sysUserVO = JsonUtils.jsonToObj(JsonUtils.objToJson(user), SysUserVO.class);
        sysUserVO.setPassword(user.getPassword());
        return new LoginUserEntity(sysUserVO, permissionService.getMenuPermission(sysUserVO));
    }
}
